package logic

import (
	"context"
	"fmt"
	"user_srv/models/cache"
	"user_srv/models/mysql"

	"user_srv/internal/svc"
	"user_srv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 修改密码
func (l *UpdatePasswordLogic) UpdatePassword(in *user.UpdatePasswordRequest) (*user.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line

	var users mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&users)

	if users.ID == 0 {
		return nil, fmt.Errorf("当前账号未注册,无法修改密码")
	}

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()
	if result != in.SmsCode {
		return nil, fmt.Errorf("当前短信验证码输入错误")
	}

	if in.Password != in.NewPassword {
		return nil, fmt.Errorf("两次密码输入不一致, 请重新输入")
	}

	if in.Password == users.Password {
		return nil, fmt.Errorf("新密码与旧密码一致, 请重新输入")
	}

	users.Password = in.Password

	mysql.DB.Debug().Updates(&users)

	return &user.UpdatePasswordResponse{
		UserId: int64(users.ID),
	}, nil
}
